package com.shimao.celnet.payment.service.apiservice;

import com.alibaba.fastjson.JSON;
import com.shimao.celnet.payment.mapper.TLRecordMapper;
import com.shimao.celnet.payment.model.Bill;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.service.PPayCustService;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import com.shimao.celnet.payment.util.CsvUtils;
import com.shimao.celnet.payment.util.ZipUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationHome;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AnalysisService {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;
    @Autowired
    private PPayCustService pPayCustService;
    @Autowired
    private TLRecordMapper tlRecordMapper;

    /*
     * 功能描述: 解析通联商户号对应的前一日账单
     * @Author: Matt
     * @Date: 2019/5/24 2:42
     */
    public void analysis(String custId){
        PPayCust cust = pPayCustService.getByCustId(custId);

        //获取运行时的同级目录
        ApplicationHome h = new ApplicationHome(getClass());
        String rootPath = h.getDir().toString();
        try {
            //获取文件下载地址
            Map<String,String> result = callOut_tlPublicService.getFileUrl(cust);
            if(!"SUCCESS".equals(result.get("retcode"))){
                logger.info("请求通联对账文件地址失败，商户Id："+custId);
                return;
            }
            //下载文件
            URL url = new URL(result.get("url"));
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);

            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            //文件保存位置
            File saveDir = new File(rootPath+"\\tlRecord\\zip\\");
            if(!saveDir.exists()){
                System.out.println(saveDir.getPath());
                saveDir.mkdirs();
            }
            String path = saveDir+File.separator+String.valueOf(new SimpleDateFormat("yyyyMMdd").format(new Date())+".zip");
            File file = new File(path);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if(fos!=null){
                fos.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
            System.out.println("info:"+url+" download success");
            //解压文件
            String filePath = ZipUtils.unZipFiles(new File(path),rootPath+"\\tlRecord\\csv\\");
            //解析文件
            List<Bill> bills = CsvUtils.csvReadOperation(filePath);
            //存入数据库
            tlRecordMapper.insertBatch(bills);
        } catch (Exception e) {
            logger.info(e.getMessage()+"-"+e.getStackTrace());
        }
    }

    /*
     * 功能描述: 读取流中的内容
     * @Author: Matt
     * @Date: 2019/5/24 2:41
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}
